package oschina

import (
	"context"
	"encoding/base64"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/chromedp/chromedp"
	"log"
	"strings"
	"time"
)

type OsChina struct {
	UserName string `json:"userName"`
	PassWord string `json:"passWord"`
}

// 登录成功并且截图
func (osChina *OsChina) Login() string {
	options := []chromedp.ExecAllocatorOption{
		chromedp.Flag("headless", false), // debug使用
	}
	options = append(chromedp.DefaultExecAllocatorOptions[:], options...)
	c, _ := chromedp.NewExecAllocator(context.Background(), options...)
	// create context
	ctx, cancel := chromedp.NewContext(c, chromedp.WithLogf(log.Printf))
	defer cancel()
	var res string
	err := chromedp.Run(ctx,
		chromedp.Navigate(`https://www.oschina.net`),
		chromedp.WaitVisible(`ul[class="user-bar__links"]`, chromedp.ByQuery),
		chromedp.InnerHTML(`ul[class="user-bar__links"]`, &res),
		//chromedp.Text(`.container-bg_lQ801`, &res, chromedp.NodeVisible),
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res)
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(res))
	if err != nil {
		log.Fatal(err)
	}
	url, _ := doc.Find("a").Attr("href")
	var buf []byte
	err = chromedp.Run(ctx,
		chromedp.Navigate(url),
		chromedp.WaitVisible(`button[class="osc-button osc-button--wide btn-submit"]`, chromedp.ByQuery),
		chromedp.Click(`div[data-osc-tab="password"]`, chromedp.ByQuery),
		chromedp.SendKeys(`input[name="username"]`, osChina.UserName, chromedp.ByQuery),
		chromedp.SendKeys(`input[name="password"]`, osChina.PassWord, chromedp.ByQuery),
		chromedp.Click(`div[class="form-box form-box--password active"] > div[class="form-box__buttons"] > button[class="osc-button osc-button--wide btn-submit"]`, chromedp.ByQuery),
		chromedp.Sleep(5*time.Second),
		chromedp.FullScreenshot(&buf, 90),
	)
	if err != nil {
		log.Fatal(err)
	}
	encoded := base64.StdEncoding.EncodeToString(buf)
	return encoded
}
